package com.ideal.gpt.app.docqajob.passage;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.ideal.gpt.GptJobConfig;
import com.ideal.gpt.ability.docqa.caller.DocQaCaller;
import com.lzwork.gpt.utility.caller.GptCallResult;
import com.lzwork.gpt.utility.common.Passage;
import com.lzwork.gpt.utility.common.Passage.CutResult;
import com.lzwork.utility.TimeTicker;
import com.lzwork.utility.collection.CollUtility;
import com.lzwork.utility.file.FileUtility;
import com.lzwork.utility.file.LineContent;
import com.lzwork.web.data.BoolResultInfo;

/**
 * @author LiZheng
 * @date 2023年11月8日 下午2:05:09
 */

public class PassageAnalyze
{
	public PassageAnalyze(String url)
	{
		caller = new DocQaCaller(url);
	}

	DocQaCaller caller;

	static String formatPrompt = "将以下文章按照段落条目拆解为json格式:";

	public BoolResultInfo callFormat(String input, boolean dolog)
	{
		List<String> content = CollUtility.arrayToList(formatPrompt, input);

		GptCallResult result = caller.callChat(content, "Passage analyze", dolog);

		if (result.getException() != null)
			return BoolResultInfo.makeFalse(result.getException().getMessage());

		return BoolResultInfo.makeTrue(result.getResponse());
	}

	public List<String> infoSplitter(String jsonStr)
	{
		List<String> lines = new ArrayList<>();
		JSONObject obj = Passage.toJObj(jsonStr);

		if (obj != null)
		{
			//
		}

		return lines;
	}

	public void doSplitFolter(File folder, File outFolder, int blockLen, int fileLimit, boolean overWrite)
	{
		File[] files = folder.listFiles();

		System.out.println("Work at folder: " + folder + " at block size: " + blockLen);

		TimeTicker ticker = new TimeTicker();

		int count = 0;
		for (int i = 0; i < files.length; i++)
		{
			File f = files[i];
			if (!f.isFile())
				continue;

			int checked = doSplitFile(f, outFolder, blockLen, overWrite, false);
			count += checked;

			if (count >= fileLimit)
				break;
		}

		System.out.println("All done. Total cost: " + ticker.tickAllS());
	}

	public int doSplitFile(File file, File outFolder, int blockLen, boolean overWrite, boolean dolog)
	{
		int count = 0;

		String name = file.getName();
		File outfile = FileUtility.getFileSafe(outFolder, file.getName());

		String fileStr = LineContent.loadString(file);

		CutResult afterCut = Passage.cutRawContent(fileStr, name, blockLen);
		int index = 0;

		if (afterCut.size() == 0)
		{
			System.out.println("File " + name + " has not passage cut result!");
			return 0;
		}

		TimeTicker ticker = new TimeTicker();

		blockloop: for (String str : afterCut)
		{
			index++;
			String suffix = "_format_" + index;

			File out = FileUtility.renameFileSafe(outfile, suffix, true);

			if (!overWrite)
			{
				if (out.exists() && out.length() > 0)
					continue blockloop;
			}

			System.out.println("Parsing " + name + " block " + index);

			String input = clearLine(str);

			BoolResultInfo info = callFormat(input, dolog);
			if (info.isDone())
			{
				File in = FileUtility.renameFileSafe(outfile, "_input_" + index, true);
				LineContent.saveFile(in, CollUtility.arrayToList(input, "", "", "", "", "", str));
				LineContent.saveFile(out, info.info());
				count++;
			} else
				System.out.println("Fail parse " + name + "[" + index + "]\t" + info.info());

			System.out.println("Block " + index + " done. Len: " + str.length() + ". Cost " + ticker.tickS());
		}

		return count;
	}

	public static void checkFolder()
	{
		File folder = new File("V:/12345/source500");

		int max = 10;
		boolean overWrite = true;

		File outFolder = FileUtility.getFileSafe(folder, "jsonFormat/");

		PassageAnalyze checker = new PassageAnalyze(GptJobConfig.getProp("url_a10x8") + ":7668");

		checker.doSplitFolter(folder, outFolder, blockSize, max, overWrite);
	}

	public static void checkSingle()
	{
		File folder = new File("V:/12345/source500");
		boolean overWrite = true;

		File outFolder = FileUtility.getFileSafe(folder, "jsonFormatSingle/");
		PassageAnalyze checker = new PassageAnalyze(GptJobConfig.getProp("url_a10x8") + ":7668");

		String name = "11505240.txt";

		checker.doSplitFile(FileUtility.getFileSafe(folder, name), outFolder, blockSize, overWrite, true);

	}

	static String clearLine(String input)
	{
		String str = input.replace("\n", " ");
		str = str.replace("　", " ");
		// str = str.replace("（", "(");
		// str = str.replace("）", ")");

		return str;
	}

	static int blockSize = 3500;

	public static void main(String[] args)
	{
		formatPrompt = "将以下文章按照段落或条目的内容拆解为json格式";
		checkFolder();

		// checkSingle();
	}
}
